<template>
    <div>
        <div class="card">
            <el-input clearable @clear="selpage" style="width: 260px; margin-right: 5px" v-model="data.username" placeholder="请输入账号查询" :prefix-icon="Search"></el-input>
            <el-input clearable                  style="width: 260px; margin-right: 5px" v-model="data.name" placeholder="请输入名称查询" :prefix-icon="Search"></el-input>
            <el-button type="primary" icon="Search" @click="selpage"/>
            <el-button @click="reset">重置</el-button>
        </div>
        <div class="card">
            <el-button type="primary" @click="handleAdd">新 增</el-button>
            <el-button type="danger" @click="deleteBatch">批量删除</el-button>
            <el-button type="info" @click="exportData">批量导出</el-button>

            <el-upload style="display: inline-block;margin-left: 10px"
                       action="http://localhost:8848/admin/import"
                       :show-file-list="false"
                       :on-success="handleImportSuccess">
                <el-button type="success" >批量导入</el-button>
            </el-upload>
        </div>

        <div class="card">
            <el-table :data="data.tableData" style="width: 100%" @selection-change="handleSelectionChange"
                      :header-cell-style="{ color: '#333', backgroundColor: '#eaf4ff' }">
                <el-table-column type="selection" width="55" />
                <el-table-column label="头像" width="80">
                    <template #default="scope">
                        <el-image :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]" :preview-teleported="true" 
                        style="width: 50px; height:50px;border-radius: 50%; "/>
                    </template>
                </el-table-column>
                <el-table-column prop="username" label="账号" width="180" />
                <el-table-column prop="name" label="名称"  />
                <el-table-column prop="phone" label="电话" />
                <el-table-column prop="email" label="邮箱" width="190" />
                <el-table-column label="操作" >
                    <template #default="scope">
                        <el-button type="primary" icon="Edit" @click="handleEdit(scope.row)"></el-button>
                        <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="card">
            <el-pagination
                v-model:current-page="data.pageNum"
                v-model:page-size="data.pageSize"
                layout="total, sizes,prev, pager, jumper"
                :total="data.total"
                @current-change="selpage"
                @size-change="selpage"
            />
        </div>
    </div>

    <!-- 添加表单弹窗 -->
    <el-dialog v-model="data.formVisible" title="管理员信息" width="500" distory-on-close>
        <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px">
            <el-form-item prop="username" label="账号" >
                <el-input v-model="data.form.username" autocomplete="off" />
            </el-form-item>
            <el-form-item prop="password" label="密码" >
                <el-input v-model="data.form.password" autocomplete="off" />
            </el-form-item>
            <el-form-item prop="name" label="名称" >
                <el-input v-model="data.form.name" autocomplete="off" />
            </el-form-item>
            <el-form-item prop="phone" label="电话号码" >
                <el-input v-model="data.form.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item prop="email" label="邮箱地址" >
                <el-input v-model="data.form.email" autocomplete="off" />
            </el-form-item>
            <el-form-item label="头像" >
                <el-upload
                    action="http://localhost:8848/files/upload"
                    :on-success="handleAvatarSuccess"
                    list-type="picture"
                    >
                    <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>

        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="data.formVisible = false">取消</el-button>
                <el-button type="primary" @click="save">保存</el-button>
            </div>
        </template>
    </el-dialog>
<!--    <div style="display: flex; align-items: center; justify-content: center">-->
<!--        <el-button>Default</el-button>-->
<!--        <el-button type="primary">Primary</el-button>-->
<!--        <el-button type="success">Success</el-button>-->
<!--        <el-button type="info">Info</el-button>-->
<!--        <el-button type="warning">Warning</el-button>-->
<!--        <el-button type="danger">Danger</el-button>-->


<!--        <div style="padding: 50px">-->
<!--            <el-icon size="25" color="green"><ChatDotRound /></el-icon>-->
<!--            &lt;!&ndash;  el-icon和el-button使用时不用导入图标  &ndash;&gt;-->
<!--            <el-icon size="25" color="green"><Calendar /></el-icon>-->
<!--            <el-button type="primary" icon="Search">按钮</el-button>-->
<!--            &lt;!&ndash;  el-input使用时需要单独导入图标✅  &ndash;&gt;-->
<!--            <div style="width: 200px">-->
<!--            <el-input  placeholder="提示placeholder" :prefix-icon="Search" :suffix-icon="Calendar" ></el-input>-->
<!--            </div>-->

<!--        </div>-->
<!--    </div>-->
</template>

<script setup>
import { reactive , ref } from "vue";
import {Plus, Search} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
    username: null,
    name: null,
    pageNum: 1,
    pageSize: 10,
    total: 0,
    tableData: [],
    formVisible:false,
    form:{},
    rules: {
        username: [
            { required: true, message: "请填写账号", trigger: "blur" }
        ],
        password: [
            { required: true, message: "请填写密码", trigger: "blur" }
        ]
    },
    rows:[]
})

const  formRef = ref()

const selpage = () =>{
    request.get('/admin/selectPage',{
        params:{
            pageNum:data.pageNum,
            pageSize:data.pageSize,
            username: data.username,
            name: data.name
        }
    }).then(res =>{
        if(res.code == '200') {
            data.tableData = res.data.list
            data.total = res.data.total
        }else {
            ElMessage.error(res.msg)
        }
    })
}
selpage()

const reset = () =>{
    data.username = null
    data.name = null
    selpage()
}

const save = () => {
    data.form.id ? update() : add()
}
const handleAdd = () =>{
 data.formVisible = true
 data.form = {}
}
const add = () =>{
    formRef.value.validate((valid) =>{
        if(valid) {
            request.post('/admin/add',data.form).then(res =>{
                if(res.code == '200') {
                    data.formVisible = false
                    ElMessage.success('新增成功')
                    selpage()
                }else {
                    ElMessage.error(res.msg)
                }
            })
        }
    })
}
const handleEdit = (row) => {
    data.form = JSON.parse(JSON.stringify(row))  //深度拷贝数据
    data.formVisible = true
}
const update = () => {
    //forRef 是表单的引用
    formRef.value.validate((valid) =>{
        if(valid) {
            request.put('/admin/update',data.form).then(res =>{
                if(res.code == '200') {
                    data.formVisible = false
                    ElMessage.success('修改成功')
                    selpage()
                }else {
                    ElMessage.error(res.msg)
                }
            })
        }
    })

}
const del = (id) => {
  ElMessageBox.confirm('删除后无法恢复，是否确认删除？', '删除确认',{type: 'waring'}).then(res =>{
      request.delete('/admin/delete/' + id).then(res => {
          if (res.code == '200') {
              ElMessage.success('删除成功')
              selpage()
          } else {
              ElMessage.error(res.msg)
          }
      })
  }).catch(err => {'已取消删除'})
}

const handleSelectionChange = (rows) =>{  //实际选择的行组成的数组
    console.log(rows)
    data.rows = rows
}
const deleteBatch = () => {
    if(data.rows.length === 0){
        ElMessage("请选择数据")
        return
    }
    ElMessageBox.confirm('❗删除后无法恢复，是否确认删除？', '删除确认').then(res =>{
        request.delete('/admin/deleteBatch',{data: data.rows }).then(res => {
            if (res.code == '200') {
                ElMessage.success('批量删除成功')
                selpage()
            } else {
                ElMessage.error(res.msg)
            }
        })
    }).catch(err => {'已取消删除'})
}

const exportData = () => {
    let url = `http://localhost:8848/admin/export?username=${data.username == null ? '' : data.username}&name=${data.name == null ? '' : data.name}`
    window.open(url)
}

const handleImportSuccess = () => {
    ElMessage.success("批量导入成功")
    selpage()
}
const handleAvatarSuccess = (res) => {
    data.form.avatar = res.data
    ElMessage.success('头像上传成功')
}
</script>

